//
//  JYJMusicManager.m
//  HappyListen
//
//  Created by 冀永金 on 16/9/19.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJMusicManager.h"
#import "JYJProgramModel.h"
#import "JYJMusicOperation.h"

static JYJMusicManager *musciManager = nil;
@interface JYJMusicManager ()<NSURLSessionDownloadDelegate> {
    NSMutableArray *_musicModels;
}

@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSMutableArray *downLoadArr;
@property (nonatomic, strong) NSString *musicPath;
@end
@implementation JYJMusicManager
+ (instancetype)shared {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        musciManager = [[self alloc]init];
    });
    return musciManager;
}
- (instancetype)init {
    if (self) {
        _musicModels = [[NSMutableArray alloc]init];
        self.queue = [[NSOperationQueue alloc]init];
        self.queue .maxConcurrentOperationCount = 4;
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        //不能传self.queue
        self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
        

        BOOL isHave = [self isHaveCurrentModel];NSLog(@"%d",isHave);
        
        if (isHave == NO) {
           _downLoadArr = [NSMutableArray array];
           
        }else {
            _downLoadArr= [[NSKeyedUnarchiver unarchiveObjectWithFile:_musicPath] mutableCopy];
        }
    }
    return self;
}

- (BOOL)isHaveCurrentModel {
    NSString *path = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    self.musicPath = [path stringByAppendingPathComponent:@"musics.plist"];
    NSFileManager *manager = [NSFileManager defaultManager];
    return [manager fileExistsAtPath:_musicPath];
}

- (NSArray *)musicModels {
    return _musicModels;
   }

- (void)addMusicModels:(NSArray<JYJProgramModel *> *)musicModels {
    if ([musicModels isKindOfClass:[NSArray class]]) {
        [_musicModels addObjectsFromArray:musicModels];
    }
}

-(void)startWithMusicModel:(JYJProgramModel *)musicModel {
    if (musicModel.status != kJYJMusicStatusCompleted ) {
        musicModel.status =  kJYJMusicStatusRunning;
        if (musicModel.operation == nil) {
            musicModel.operation = [[JYJMusicOperation alloc]initWithModel:musicModel session:self.session];
           [self.queue addOperation:musicModel.operation];
            [musicModel.operation start];
        }else {
            [musicModel.operation resume];
        }
    }
}
- (void)suspendWithMusicModel:(JYJProgramModel *)musicModel {
    if (musicModel.status != kJYJMusicStatusCompleted) {
        [musicModel.operation suspend];
    }
}
-(void)resumeWithMusicModel:(JYJProgramModel *)musicModel {
    if (musicModel.status != kJYJMusicStatusCompleted ) {
        [musicModel.operation resume];
    }
}
- (void)stopWithMusicModel:(JYJProgramModel *)musicModel {
    if (musicModel.operation) {
        [musicModel.operation cancel];
    }
}

#pragma mark ------NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    //本地的文件路径，使用fileURLWithPath:
    if (downloadTask.jyj_programModel.localPath) {
        NSURL *toURL = [NSURL fileURLWithPath:downloadTask.jyj_programModel.localPath];
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager moveItemAtURL:location toURL:toURL error:nil];
        
    }

     NSArray *pathArr =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    JYJProgramModel *model = [JYJProgramModel new];
    model.music_title = downloadTask.jyj_programModel.music_title;
    model.music_id = downloadTask.jyj_programModel.music_id;
    model.music_img = downloadTask.jyj_programModel.music_img;
    _musicPath = [[pathArr firstObject] stringByAppendingPathComponent:@"musics.plist"];
    [_downLoadArr addObject:model];
    [NSKeyedArchiver archiveRootObject:_downLoadArr toFile:_musicPath];

    NSLog(@"%@",_musicPath);
    
    [downloadTask.jyj_programModel.operation downloadFinished];
    
    NSLog(@"path==%@",downloadTask.jyj_programModel.localPath);
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error == nil) {
            task.jyj_programModel.status =  kJYJMusicStatusCompleted;
            [task.jyj_programModel.operation downloadFinished];
        }else if (task.jyj_programModel.status == kJYJMusicStatusSuspended) {
            task.jyj_programModel.status = kJYJMusicStatusSuspended;
        }else if ([error code] < 0){
            //网络异常
            task.jyj_programModel.status =  kJYJMusicStatusFailed;
        }
    });
}
- (void)URLSession:(NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    double byts = totalBytesWritten * 1.0 /1024 / 1024;
    double total = totalBytesExpectedToWrite * 1.0 /1024 / 1024;
    NSString *text = [NSString stringWithFormat:@"%.1lfMB/%.1lfMB",byts,total];
    CGFloat proess = totalBytesWritten / (CGFloat) totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
        downloadTask.jyj_programModel.progressText = text;
        downloadTask.jyj_programModel.progress = proess;
    });
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
    double byts = fileOffset * 1.0 / 1024 / 1024;
    double total = expectedTotalBytes * 1.0 /1024 / 1024;
   NSString *text = [NSString stringWithFormat:@"%.1lfMB/%.1lfMB",byts,total];
    CGFloat progress  =fileOffset / (CGFloat)expectedTotalBytes;
    dispatch_async(dispatch_get_main_queue(), ^{
        downloadTask.jyj_programModel.progressText = text;
        downloadTask.jyj_programModel.progress = progress;
    });

}

@end
